package com.xzx.controller;

import com.xzx.enu.ErrorCode;
import com.xzx.exception.RestRuntimeException;
import com.xzx.po.UserPO;
import com.xzx.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/8/18 17:59
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @PostMapping("/doLogin")
    public String doLogin(@RequestBody UserPO userPO, HttpServletRequest request) {
        if (StringUtils.isBlank(userPO.getAccount()) || StringUtils.isBlank(userPO.getPwd())) {
            throw new RestRuntimeException(ErrorCode.USERNAME_PASSWORD_NOT_NULL);
        }
        if (userService.doLogin(userPO, request)) {
            return "ok";
        }
        throw new RestRuntimeException(ErrorCode.USERNAME_PASSWORD_ERROR);
    }

    @GetMapping("/doLogout")
    public String doLogout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:" + request.getContextPath() + "/login";
    }
}
